package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
    @Autowired
    private FileService fileService;

    @Override
    public List<Item> testFindAll() {
        return itemMapper.selectList(null);
    }

    @Override
    public PageResult getItemList(PageResult pageResult) {
        //获取分页对象，传入分页查询条件，查询页数及显示条数
        Page<Item> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        //设定判断条件，判断Query是否有值，若为空则不拼接
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        //拼接where条件
        wrapper.like(flag, "title", pageResult.getQuery());
        //传入分页对象和查询条件进行分页查询，获取已经封装了所有数据的分页对象
        Page<Item> itemPage = itemMapper.selectPage(page, wrapper);
        //从返回的分页对象中获取我们需要返回的数据，封装金分页结果对象里，返回pageResult即可
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getRecords());
        return pageResult;
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Item item) {
        itemMapper.deleteById(item);
        itemDescMapper.deleteById(item.getId());
        fileService.deleteFile(item.getImages());
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);
        /*mybatis可以在mapper中写SQL实现业务功能，自动回显主键*/

         /** 但是mybatis-plus可以自动实现主键回显*/
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }
}
